package cn.vshare.util;

import java.io.*;

public class MyThread extends Thread {
    private Process process;
    private VideoUtil videoUtil;
    private String begingFilePath;
    private String videoUtilId;

    public MyThread(Process process, VideoUtil videoUtil, String begingFilePath, String videoUtilId) {
        this.process = process;
        this.videoUtil = videoUtil;
        this.begingFilePath = begingFilePath;
        this.videoUtilId=videoUtilId;
    }

    public void run() {
        VideoUtil.currTimeMap.put(videoUtilId,videoUtil);
        String totalTime = videoUtil.getTotalTime();
        String currTime = videoUtil.getCurrTime();
        String finish = videoUtil.getFinish();
        int n = -1;
        InputStream in = process.getErrorStream();
        InputStreamReader inr = new InputStreamReader(in);
        BufferedReader br = new BufferedReader(inr);
        String line = null;
        try {
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                if (n == -1) {
                    n = line.indexOf("Duration");
                    if (n != -1) {
                        totalTime = line.substring((10 + n), (21 + n));
                        totalTime = totalTime.substring(3, 5);
                        videoUtil.setTotalTime(totalTime);
                        System.out.println("-----------" + totalTime);
                    }
                }
                int tn = line.indexOf("time=");
                System.out.println(tn);
                if (tn > 5) {
                    currTime = line.substring(tn + 8, tn + 10);
                    videoUtil.setCurrTime(currTime);
                    System.out.println(currTime);
                }
                int en = line.indexOf("overhead");
                if (en > 5) {
                    finish = "yes";
                    System.out.println(finish);
                    videoUtil.setFinish(finish);
                }
                VideoUtil.currTimeMap.put(videoUtilId,videoUtil);
            }

            if ("yes".equals(finish)) {
                System.out.println("----------------" + finish);
                br.close();
                process.destroy();
                System.out.println("----------------" + 2);
                File file = new File(begingFilePath);
                System.out.println("----------------" + 3);
                file.delete();
                System.out.println("----------------" + 4);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
